package org.lqk.netty.simple.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * Created by bert on 16/12/20.
 */
public class TimeClient {
    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new TimeHandler());
                        }
                    });
            // bootstrap connnect ==> AbstractChannel connect ==>  channel.eventLoop().execute  ==> pipeline connect ==>
            // head(channnel handler) connect ==> unsafe oonnect ==> nio socket channel doConnect

            /*
                从这个过程能看出什么呢?
                1. 几个io操作,实际都是channel实现的,方法都是线程安全
                2. 一个channel绑定了一个线程,因此channel io方法的线程安全,最终都要有一个特定的线程执行
                3. unsafe,之所以取名UnSafe是因为不能从外部线程调用UnSafe接口中的方法，只能在Channel当前相关的I/O线程中调用
                4. 前一个能调用下一个,是因为前一个聚合了下一个的操作对象
             */

            ChannelFuture f = b.connect("localhost", 9000).sync();
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}
